<template>
  <div class="application-list">
    <div v-if="applications.length === 0" class="empty-applications">
      <el-empty :description="emptyText" />
    </div>
    
    <div v-else>
      <el-table
        :data="applications"
        style="width: 100%"
        :default-sort="{ prop: 'created_at', order: 'descending' }"
      >
        <el-table-column label="宠物信息" min-width="200">
          <template #default="{ row }">
            <div class="pet-info">
              <div class="pet-image-container" v-if="row.pet && row.pet.image_url">
                <img :src="getPetImageUrl(row.pet)" alt="宠物图片" class="pet-image">
              </div>
              <div class="pet-details">
                <span class="pet-name">{{ row.pet ? row.pet.name : '未知宠物' }}</span>
                <span class="pet-breed" v-if="row.pet && row.pet.breed">{{ row.pet.breed }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row.status)"
              effect="plain"
            >
              {{ formatStatus(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="created_at" label="申请时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="updated_at" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.updated_at) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button link @click="viewApplication(row.id)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 查看详情对话框 -->
    <el-dialog
      :title="'申请详情'"
      v-model="dialogVisible"
      width="60%"
      :before-close="handleDialogClose"
    >
      <div v-if="loadingDetails" class="dialog-loading">
        <el-skeleton :rows="10" animated />
      </div>
      
      <div v-else-if="currentApplication">
        <div class="dialog-content">
          <div class="dialog-section">
            <h3>宠物信息</h3>
            <div class="pet-info-dialog">
              <div class="pet-image-container-dialog" v-if="currentApplication.pet && currentApplication.pet.image_url">
                <img :src="getPetImageUrl(currentApplication.pet)" alt="宠物图片" class="pet-image-dialog">
              </div>
              <div class="pet-details-dialog">
                <div class="info-row">
                  <span class="info-label">名称:</span>
                  <span class="info-value">{{ currentApplication.pet ? currentApplication.pet.name : '未知' }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">品种:</span>
                  <span class="info-value">{{ currentApplication.pet && currentApplication.pet.breed ? currentApplication.pet.breed : '未知' }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">性别:</span>
                  <span class="info-value">{{ formatGender(currentApplication.pet ? currentApplication.pet.gender : null) }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">年龄:</span>
                  <span class="info-value">{{ currentApplication.pet && currentApplication.pet.age ? `${currentApplication.pet.age} 岁` : '未知' }}</span>
                </div>
              </div>
            </div>
          </div>
          
          <div class="dialog-section">
            <h3>申请状态</h3>
            <div class="status-info">
              <el-tag :type="getStatusType(currentApplication.status)" size="large" effect="plain">
                {{ formatStatus(currentApplication.status) }}
              </el-tag>
              <div class="status-info-item">
                <span class="info-label">申请时间:</span>
                <span class="info-value">{{ formatDate(currentApplication.created_at) }}</span>
              </div>
              <div class="status-info-item">
                <span class="info-label">更新时间:</span>
                <span class="info-value">{{ formatDate(currentApplication.updated_at) }}</span>
              </div>
              <div class="status-info-item" v-if="currentApplication.status_reason">
                <span class="info-label">状态说明:</span>
                <span class="info-value">{{ currentApplication.status_reason }}</span>
              </div>
            </div>
          </div>
          
          <div class="dialog-section">
            <h3>申请人信息</h3>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="姓名">{{ currentApplication.name }}</el-descriptions-item>
              <el-descriptions-item label="电话">{{ currentApplication.phone }}</el-descriptions-item>
              <el-descriptions-item label="邮箱">{{ currentApplication.email }}</el-descriptions-item>
              <el-descriptions-item label="居住地址">{{ currentApplication.address }}</el-descriptions-item>
              <el-descriptions-item label="职业">{{ currentApplication.occupation }}</el-descriptions-item>
              <el-descriptions-item label="居住情况">{{ formatLivingSituation(currentApplication.living_situation) }}</el-descriptions-item>
              <el-descriptions-item label="家庭成员">{{ currentApplication.family_members }} 人</el-descriptions-item>
              <el-descriptions-item label="养宠经验">{{ currentApplication.pet_experience ? '有' : '无' }}</el-descriptions-item>
            </el-descriptions>
          </div>
          
          <div class="dialog-section" v-if="currentApplication.pet_experience && currentApplication.experience_description">
            <h3>养宠经验描述</h3>
            <p class="description-text">{{ currentApplication.experience_description }}</p>
          </div>
          
          <div class="dialog-section">
            <h3>领养原因</h3>
            <p class="description-text">{{ currentApplication.reason_for_adoption || '未填写' }}</p>
          </div>
          
          <div class="dialog-section">
            <h3>可提供的生活环境</h3>
            <p class="description-text">{{ currentApplication.living_situation || '未填写' }}</p>
          </div>

          <div class="dialog-section" v-if="currentApplication.previous_pet_experience">
            <h3>养宠经验</h3>
            <p class="description-text">{{ currentApplication.previous_pet_experience }}</p>
          </div>

          <div class="dialog-section" v-if="currentApplication.additional_notes">
            <h3>补充信息</h3>
            <p class="description-text">{{ currentApplication.additional_notes }}</p>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button 
            type="primary" 
            v-if="currentApplication && currentApplication.status === 'approved'"
            @click="goToMyPets"
          >
            查看我的宠物
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions, mapGetters } from 'vuex';

export default {
  name: 'ApplicationList',
  props: {
    applications: {
      type: Array,
      required: true
    },
    emptyText: {
      type: String,
      default: '没有申请记录'
    }
  },
  data() {
    return {
      dialogVisible: false,
      loadingDetails: false,
      currentApplication: null
    };
  },
  computed: {
    ...mapGetters({
      applicationDetails: 'adoptions/getCurrentApplication'
    })
  },
  methods: {
    ...mapActions({
      fetchApplication: 'adoptions/fetchApplication'
    }),
    formatStatus(status) {
      const statusMap = {
        'pending': '待审核',
        'approved': '已通过',
        'rejected': '已拒绝'
      };
      return statusMap[status] || '未知';
    },
    getStatusType(status) {
      const typeMap = {
        'pending': 'warning',
        'approved': 'success',
        'rejected': 'danger'
      };
      return typeMap[status] || 'info';
    },
    formatDate(dateString) {
      if (!dateString) return '未知';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN');
    },
    formatGender(gender) {
      const genderMap = {
        'male': '公',
        'female': '母'
      };
      return genderMap[gender] || '未知';
    },
    formatLivingSituation(situation) {
      const situationMap = {
        'own': '自有住房',
        'rent': '租房',
        'family': '与家人同住',
        'other': '其他'
      };
      return situationMap[situation] || '未知';
    },
    getPetImageUrl(pet) {
      if (!pet || !pet.image_url) {
        return 'https://via.placeholder.com/100x100?text=No+Image';
      }
      
      // 检查是否为完整URL
      if (pet.image_url.startsWith('http')) {
        return pet.image_url;
      }
      
      // 确保URL格式正确
      const apiUrl = process.env.VUE_APP_API_URL || 'http://localhost:3000';
      // 确保image_url是以/开头的路径
      const imagePath = pet.image_url.startsWith('/') ? pet.image_url : `/${pet.image_url}`;
      return `${apiUrl}${imagePath}`;
    },
    async viewApplication(id) {
      this.loadingDetails = true;
      this.dialogVisible = true;
      
      try {
        const result = await this.fetchApplication(id);
        this.currentApplication = result;
      } catch (error) {
        console.error('获取申请详情失败', error);
        this.$message.error('获取申请详情失败');
      } finally {
        this.loadingDetails = false;
      }
    },
    handleDialogClose() {
      this.dialogVisible = false;
      this.currentApplication = null;
    },
    goToMyPets() {
      this.$router.push('/my-pets');
    }
  }
}
</script>

<style lang="scss" scoped>
.application-list {
  margin-top: 20px;
}

.empty-applications {
  min-height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.pet-info {
  display: flex;
  align-items: center;
}

.pet-image-container {
  width: 50px;
  height: 50px;
  margin-right: 10px;
  border-radius: 4px;
  overflow: hidden;
  flex-shrink: 0;
}

.pet-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.pet-details {
  display: flex;
  flex-direction: column;
}

.pet-name {
  font-weight: bold;
  color: var(--text-color);
}

.pet-breed {
  font-size: 0.8rem;
  color: var(--gray-color);
}

.dialog-loading {
  padding: 20px;
}

.dialog-content {
  max-height: 60vh;
  overflow-y: auto;
  padding: 0 5px;
}

.dialog-section {
  margin-bottom: 20px;
  
  h3 {
    margin-bottom: 15px;
    color: var(--secondary-color);
    border-bottom: 1px solid #eee;
    padding-bottom: 8px;
  }
}

.pet-info-dialog {
  display: flex;
  margin-bottom: 15px;
}

.pet-image-container-dialog {
  width: 100px;
  height: 100px;
  margin-right: 15px;
  border-radius: 4px;
  overflow: hidden;
  flex-shrink: 0;
}

.pet-image-dialog {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.pet-details-dialog {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.info-row {
  margin-bottom: 5px;
  display: flex;
}

.info-label {
  font-weight: bold;
  width: 60px;
  color: var(--gray-color);
}

.info-value {
  flex-grow: 1;
}

.status-info {
  display: flex;
  flex-direction: column;
  gap: 10px;
  
  .el-tag {
    margin-bottom: 10px;
  }
}

.status-info-item {
  display: flex;
}

.description-text {
  white-space: pre-line;
  color: var(--text-color);
  line-height: 1.6;
}
</style> 